package com.outsource.framework.util.unicom.news.sms;

import java.io.Serializable;
import java.util.Random;

import org.amplatform.common.exception.BpoException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.outsource.framework.util.common.Constants;

public class SessionSmsValider implements Serializable{

	private static final long serialVersionUID = 1L;

	private static Log log = LogFactory.getLog(SessionSmsValider.class);

	private long MIN_SEND_SMS_DELAY = 30 * 1000;
	private int MAX_SEND_COUNTS = 5;
	private long lastSendTime;
	private int sendTimes;
	private String validCode;
	private String mobile;
	
	public SessionSmsValider(String mobile)
	{
		this.mobile = mobile;
	}
	public String send(SmsClient client)
	{
		if (System.currentTimeMillis() - lastSendTime < MIN_SEND_SMS_DELAY)
		{
			return Constants.SMS_SEND_SUCCESS;
		} else
		{
			if (sendTimes >= MAX_SEND_COUNTS)
			{
				return Constants.SMS_SEND_MANY;
			}
		}

		validCode = getRandSms();
		log.info("send sms code:" + validCode + "\t for mobile:" + mobile);
		try
		{
			client.sendSms(mobile, Constants.SMS_SEND_VALIDATE + validCode);
			
		} catch (BpoException e)
		{
			e.printStackTrace();
			return Constants.SMS_SEND_ERROR;
		}

		lastSendTime = System.currentTimeMillis();
		sendTimes++;
		return null;
	}

	private String getRandSms()
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 4; i++)
		{
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}

	private static Random random = new Random();

	public boolean isValid(String mobile, String smsCode)
	{
		if (this.mobile.equals(mobile) && validCode.equals(smsCode))
		{
			return true;
		} else
		{
			return false;
		}
	}


	public long getLastSendTime()
	{
		return lastSendTime;
	}

	public void setLastSendTime(long lastSendTime)
	{
		this.lastSendTime = lastSendTime;
	}

	public int getSendTimes()
	{
		return sendTimes;
	}

	public void setSendTimes(int sendTimes)
	{
		this.sendTimes = sendTimes;
	}

	public String getValidCode()
	{
		return validCode;
	}

	public void setValidCode(String validCode)
	{
		this.validCode = validCode;
	}

	public String getMobile()
	{
		return mobile;
	}

	public void setMobile(String mobile)
	{
		this.mobile = mobile;
	}
	
}
